<template>
  <el-dialog title="标题" :visible="dialogVisible" width="35%" @close="closeDialog">

    <el-form ref="writeForm" :model="formData" :rules="rules" label-width="100px" size="small">
      <el-form-item prop="name" label="部门名称">
        <el-input v-model="formData.name" />
      </el-form-item>
      <el-form-item prop="code" label="部门编码">
        <el-input v-model="formData.code" />
      </el-form-item>
      <el-form-item prop="managerId" label="部门负责人">
        <el-select v-model="formData.managerId" style="width: 80%;" placeholder="请选择部门负责人">
          <el-option v-for="item in managerList" :key="item.id" :label="item.username" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item prop="introduce" label="部门介绍">
        <el-input v-model="formData.introduce" :rows="4" type="textarea" />
      </el-form-item>
      <el-row type="flex" justify="center">
        <el-button type="primary" @click="writeDepartment">确定</el-button>
        <el-button @click="closeDialog">取消</el-button>
      </el-row>
    </el-form>
  </el-dialog>
</template>
<script>
import { getManagerList, addDepartment, getDepartment, editDepartment } from '@/api/department'

export default {
  props: {
    dialogVisible: {
      type: Boolean,
      default: false
    },
    deptList: {
      type: Array,
      default: () => []
    },
    pidTaken: {
      type: Number,
      required: true
    }
  },
  data() {
    return {
      formData: {
        code: '',
        introduce: '',
        managerId: '',
        name: '',
        pid: this.pidTaken
      },
      rules: {
        name: [
          { required: true, message: '请输入部门名称', trigger: 'blur' },
          { min: 3, max: 18, message: '部门名称长度为4-18个字符', trigger: 'blur' },
          {
            trigger: 'blur',
            validator: (rule, value, callback) => {
              if (this.formData.id) {
                // 编辑部门校验规则
                // 排除掉自身，再判断一个部门下的部门名称是否重复
                const excludeSelfDeptList = this.deptList.filter(item => !(item.name === value && item.pid === this.formData.pid))
                if (excludeSelfDeptList.every(item => !(item.name === value && item.pid === this.formData.pid))) {
                  callback()
                } else {
                  callback(new Error('部门名称已存在'))
                }
              } else {
                // 新增部门校验规则
                // 判断一个部门下的部门名称是否重复
                if (this.deptList.every(item => !(item.name === value && item.pid === this.formData.pid))) {
                  callback()
                } else {
                  callback(new Error('部门名称已存在'))
                }
              }
            }
          }],
        code: [
          { required: true, message: '请输入部门编码', trigger: 'blur' },
          { min: 3, max: 18, message: '部门编码长度为4-18个字符', trigger: 'blur' },
          {
            trigger: 'blur',
            validator: (rule, value, callback) => {
              if (this.formData.id) {
                // 编辑部门校验规则
                // 排除掉自身，再判断部门编码是否重复
                const excludeSelfDeptList = this.deptList.filter(item => !(item.code === value))
                if (excludeSelfDeptList.every(item => item.code !== value)) {
                  callback()
                } else {
                  callback(new Error('部门编码已存在'))
                }
              } else {
                // 新增部门校验规则
                // 判断部门编码是否重复
                if (this.deptList.every(item => item.code !== value)) {
                  callback()
                } else {
                  callback(new Error('部门编码已存在'))
                }
              }
            }
          }],
        managerId: [{ required: true, message: '请选择部门负责人', trigger: 'blur' }],
        introduce: [{ required: true, message: '请输入部门介绍', trigger: 'blur' }]
      },
      managerList: []
    }
  },
  watch: {
    pidTaken(newValue, oldValue) {
      this.formData.pid = newValue
    }
  },
  created() {
    this.getManagerList()
  },
  methods: {
    // 关闭弹层
    closeDialog() {
      this.$emit('update:dialogVisible', false)
      this.$refs.writeForm.resetFields() // 只能清空v-model绑定的表单项，隐藏的如id就无法清空
    },

    // 获取下拉选项内容管理者列表
    async getManagerList() {
      this.managerList = await getManagerList()
    },

    // 获取某个节点的数据，用户编辑部门时回显数据
    async getDepartment(id) {
      this.formData = await getDepartment(id)
    },
    // 新增、编辑部门确认按钮
    writeDepartment() {
      // 当校验通过才提交
      this.$refs.writeForm.validate(async(isOk) => {
        if (isOk) {
          let msg = ''
          if (this.formData.id) {
            // 编辑部门
            msg = '修改'
            await editDepartment(this.formData)
          } else {
            // 新增部门
            msg = '新增'
            await addDepartment(this.formData)
          }
          this.$message({
            type: 'success',
            message: `${msg}部门成功`
          })
          // 刷新列表数据
          this.$emit('updateDepartment')
          this.closeDialog()
        }
      })
    }

  }
}
</script>
